package com.example.openguass.controller;

import com.example.openguass.entity.CommonResult;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Calendar;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/picture")
@Api(value = "PictureController", tags = "照片接口")
public class PictureController {

    @PostMapping(value = "/upload")
    public CommonResult upload(@RequestPart(value = "file") MultipartFile file, HttpServletRequest request) {
        CommonResult result = new CommonResult().init();
        Calendar currTime = Calendar.getInstance();
        String time = String.valueOf(currTime.get(Calendar.YEAR))+String.valueOf((currTime.get(Calendar.MONTH)+1));
        String path = new String();
        if (System.getProperties().getProperty( "os.name" ).contains("Windows")){
            path ="D:\\src"+ File.separator+"img"+File.separator+time;
        }else if (System.getProperties().getProperty( "os.name" ).contains("Linux")){
            path ="/usr/local/"+ File.separator+"img"+File.separator+time;
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        suffix = suffix.toLowerCase();
        if(suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals(".png") || suffix.equals(".gif")){
            String fileName = UUID.randomUUID().toString()+suffix;
            File targetFile = new File(path, fileName);
            if(!targetFile.getParentFile().exists()){    //注意，判断父级路径是否存在
                targetFile.getParentFile().mkdirs();
            }
            long size = 0;
            //保存
            try {
                file.transferTo(targetFile);
                result.success("filePath","http://43.142.99.39:8080/pictures/"+time+"/"+fileName);
                size = file.getSize();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            result.failCustom(-10086,"文件格式不支持");
        }
        return result;
    }
}
